package com.sctvcloud.linshui.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.Gson;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.linshui.R;
import com.sctvcloud.linshui.application.Constances;
import com.sctvcloud.linshui.beans.FarmerHouseChannel;
import com.sctvcloud.linshui.beans.GovDetailBean;
import com.sctvcloud.linshui.beans.HomeListItem;
import com.sctvcloud.linshui.beans.NewsClickCountBean;
import com.sctvcloud.linshui.beans.NewsIdBean;
import com.sctvcloud.linshui.beans.NewsItem;
import com.sctvcloud.linshui.beans.NewsListClickRequestBean;
import com.sctvcloud.linshui.beans.NewsListClickVo;
import com.sctvcloud.linshui.http.AbsListNetCallback;
import com.sctvcloud.linshui.http.AbsNetCallBack;
import com.sctvcloud.linshui.http.NetUtils;
import com.sctvcloud.linshui.ui.activities.CultureTravelActivity;
import com.sctvcloud.linshui.ui.activities.FindFellowVillagersActivity;
import com.sctvcloud.linshui.ui.activities.LoginActivity;
import com.sctvcloud.linshui.ui.adapter.FarmerHouseAdapter;
import com.sctvcloud.linshui.ui.adapter.holder.FarmersEntrysHolder;
import com.sctvcloud.linshui.ui.adapter.holder.FindFellowVillagersHolder;
import com.sctvcloud.linshui.ui.util.IListShowData;
import com.sctvcloud.linshui.utils.UserManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 农民工之家
 */
public class FarmerHouseFragment extends ColumnBaseFragment implements CanRefreshLayout.OnRefreshListener
        , CanRefreshLayout.OnLoadMoreListener, FindFellowVillagersHolder.OnFindFellowVillagersClickListener, FarmersEntrysHolder.OnFarmersEntrysClickListener {
    @BindView(R.id.common_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView recyclerView;
    private int mPageNo = 0;
    private int mPageAll = 0;
    private FarmerHouseAdapter adapter;
    private String newsUrlTemp;
    private LinearLayoutManager layoutManager;
    private List<IListShowData> greatList = new ArrayList<>();
    private List<GovDetailBean> entryList = new ArrayList<>();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_farmers_house, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
    }


    @Override
    public void onLoadMore() {
        mPageNo++;
        getNewsData();
    }

    @Override
    public void onRefresh() {
        mPageNo = 0;
        greatList.clear();
        entryList.clear();
        getChannelList();
    }

    @Override
    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
        layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        adapter = new FarmerHouseAdapter(getContext(), null, this);
        adapter.setFarmersEntrysClickListener(this);
        adapter.setFindFellowVillagersClickListener(this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    protected boolean onFragmentShow(boolean isFirst, boolean isCallFromResume) {
        if (isFirst) {
            //首次显示的时候，自动刷新数据
            refreshLayout.autoRefresh();
        }
        return super.onFragmentShow(isFirst, isCallFromResume);
    }


    /**
     * 获取精选模块 多个类型的显示数据。
     */
    private void getChannelList() {
        if (TextUtils.isEmpty(channelUrl)) {
            toast("数据错误");
            JLog.e("int " + this.getClass().getSimpleName() + " url wrong ::" + channelUrl);
            refreshLayout.refreshComplete();
            return;
        }
        NetUtils.getNetAdapter().getFarmerHouseChannel(getOwnerName(), channelUrl, new AbsNetCallBack<FarmerHouseChannel>(FarmerHouseChannel.class) {
            @Override
            public void onSuc(FarmerHouseChannel channel) {
                if (null != channel && ListUtils.isListValued(channel.getInstitutionList())) {
                    resetUrlTemps();
                    List<GovDetailBean> list = channel.getInstitutionList();
                    for (GovDetailBean fc : list) {
                        if (fc != null) {
                            switch (fc.getUuid()) {
                                case "0":
                                    entryList.add(fc);
                                    break;
                                case "1":
                                    newsUrlTemp = fc.getInstitutionUrl();
                                    break;
                                default:
                                    newsUrlTemp = fc.getInstitutionUrl();
                                    break;
                            }
                        }
                    }

                    initFindFellow();
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                refreshLayout.refreshComplete();
            }
        });
    }

    private void initFindFellow() {
        //找老乡
        HomeListItem hb = new HomeListItem();
        hb.setViewType(FarmerHouseAdapter.VIEWTYPE_FIND_FELLOW_VILLAGERS);
        greatList.add(hb);
        initEntryData();
    }

    private void initEntryData() {
        HomeListItem entry = new HomeListItem();
        entry.setViewType(FarmerHouseAdapter.VIEWTYPE_ENTRY);
        entry.setChannelList(entryList);
        greatList.add(entry);
        getNewsData();
    }

    private void getNewsData() {
        NetUtils.getNetAdapter().getNewsPage(getOwnerName(), newsUrlTemp, mPageNo, new AbsListNetCallback<NewsItem>(null) {
            @Override
            public void onSuc(List<NewsItem> newsItems) {
                if (!ListUtils.isListValued(newsItems)) {
                    initData();
                    onError(null, null);
                    return;
                }
                if (mPageAll == 0) {
                    mPageAll = getPageResponse().getData().getPageAll();
                }
                requestNewsClickCount(newsItems);

            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                if (mPageNo > 0) {
                    mPageNo--;
                }
            }

            @Override
            public void onEnd() {
                onNetFinish();
            }
        });
    }

    private void initData() {
        adapter.setDatass(greatList);
    }

    private List<NewsItem> newsItems;

    /**
     * 获取新闻列表点击量
     *
     * @param list
     */
    private void requestNewsClickCount(final List<NewsItem> list) {
        if (ListUtils.isListValued(list)) {
            newsItems = new ArrayList<>();
            newsItems.addAll(list);
            List<NewsIdBean> newsIdList = new ArrayList<>();
            NewsIdBean newsBean;
            for (int i = 0; i < list.size(); i++) {
                String type = "10";//默认不返回点击量
                if (list.get(i) instanceof NewsItem) {
                    NewsItem item = (NewsItem) list.get(i);
                    newsBean = new NewsIdBean();
                    newsBean.setId(item.getUrlNewsId());
                    switch (item.getNewsType()) {
                        case Constances.NEWS_TYPE_GRAPHIC:
                        case Constances.NEWS_TYPE_AUDIO:
                        case Constances.NEWS_TYPE_VIDEO:
                            //新闻详情
                            type = "0";
                            break;
                        case Constances.NEWS_TYPE_LIVE:
                            //直播详情
                            type = "1";
                            break;
                        case Constances.NEWS_TYPE_H5:
                            //新闻详情
                            type = "0";
                            newsBean.setId(item.getNewsId());
                            break;
                        default:
                            //其他详情
                            newsBean.setId(item.getNewsId());
                            type = "10";
                            break;
                    }
                    newsBean.setType(type);
                    newsIdList.add(newsBean);
                } else {
                    newsBean = new NewsIdBean();
                    newsBean.setId("1");
                    newsBean.setType(type);
                    newsIdList.add(newsBean);
                }
            }
            if (ListUtils.isListValued(newsIdList)) {
                NewsListClickRequestBean requestBean = new NewsListClickRequestBean();
                requestBean.setNewsIds(newsIdList);
                Gson gson = new Gson();
                String newsId = gson.toJson(requestBean);
                RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), newsId);
                NetUtils.getNetAdapter().getViewsList(getOwnerName(), body, new AbsNetCallBack<NewsListClickVo>(NewsListClickVo.class) {
                    @Override
                    public void onSuc(NewsListClickVo newsListClickVo) {
                        if (null != newsListClickVo && ListUtils.isListValued(newsListClickVo.getResult())) {
                            List<NewsClickCountBean> countList = newsListClickVo.getResult();
                            for (int i = 0; i < countList.size(); i++) {
                                if (!TextUtils.isEmpty(countList.get(i).getId()) && newsItems.get(i) instanceof NewsItem) {
                                    NewsItem item = (NewsItem) newsItems.get(i);
                                    if (item.getNewsType() == Constances.NEWS_TYPE_H5) {
                                        if (countList.get(i).getId() != null && countList.get(i).getId().equalsIgnoreCase(item.getNewsId())) {
                                            ((NewsItem) newsItems.get(i)).setReadCount(countList.get(i).getViews());
                                        }
                                    } else if (countList.get(i).getId() != null && countList.get(i).getId().equalsIgnoreCase(item.getUrlNewsId())) {
                                        ((NewsItem) newsItems.get(i)).setReadCount(countList.get(i).getViews());
                                    }
                                }
                            }
                        }


                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        if (ListUtils.isListValued(newsItems)) {
                            greatList.addAll(newsItems);
                        }
                        initData();
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg) {
                        super.onError(ex, errorMsg);
                    }
                });
            }
        }
    }


    private synchronized void onNetFinish() {
        refreshLayout.refreshComplete();
        refreshLayout.loadMoreComplete();
        refreshLayout.setLoadMoreEnabled(mPageNo+1 >= mPageAll ? false : true);
    }

    private void resetUrlTemps() {
        newsUrlTemp = null;

    }

    @Override
    public void OnFarmersEntryClick(int clickPosition) {
        if (ListUtils.isListValued(entryList) && entryList.size() > clickPosition) {
            Intent intent = new Intent(getContext(), CultureTravelActivity.class);
            intent.putExtra(CultureTravelActivity.CHANNEL_NAME, entryList.get(clickPosition).getInstitutionName());
            intent.putExtra(CultureTravelActivity.CHANNEL_ID, entryList.get(clickPosition).getInstitutionId());
            startActivity(intent);
        }

    }

    @Override
    public void OnFindFellVillClick() {
        //TODO 找老乡
        if (null != UserManager.getInstance().getUser()) {
            Intent intent = new Intent(getContext(), FindFellowVillagersActivity.class);
            startActivity(intent);
        } else {
            Intent intent = new Intent(getContext(), LoginActivity.class);
            startActivity(intent);
        }
    }
}
